import koaRouter from 'koa-router'
import { query, escape, sqlErrorCode } from '@/utils/mySqlConnection'
import { errorRes, successRes } from '@/utils/responseModel'
import { CustomRouterContext } from './index'
import { bodyNotNull } from '@/utils/utils'
import { dataSource } from '@/utils/typeormConnect'
import { Attr } from '@/model/Attr'
import { Group } from '@/model/Group'

const router = new koaRouter<any, CustomRouterContext>()

const attrRepository = dataSource.getRepository(Attr)
const groupRepository = dataSource.getRepository(Group)

router.prefix('/attr')

// TODO 未完成
router.post('/list', async (ctx, next) => {
    const { userId } = ctx.global.tokenInfo
    await groupRepository
        .createQueryBuilder('g')
        .select('g.name', 'groupName')
        .addSelect('g.id', 'groupId')
        .addSelect('a.name', 'attrName')
        .addSelect('a.id', 'attrId')
        .leftJoin(Attr, 'a', 'g.id = a.groupId')
        .where('g.userId = :userId', { userId })
        .andWhere('g.state = 1')
        .getRawMany().then(r => {
            const map = new Map()
            r.forEach(item => {
                const { groupName, groupId, attrName, attrId } = item
                if (!map.has(item.groupId)) map.set(item.groupId, { groupName, groupId, children: [] })
                if (item.attrId || item.attrId === 0) {
                    const value = map.get(item.groupId)
                    value.children.push({ attrName, attrId })
                }
            })
            ctx.body = new successRes(Array.from(map.values()))
        })
})

router.post('/addAttr', async (ctx, next) => {
    const { groupId, attrName, inputType, values } = ctx.request.body as {
        groupId: number,
        attrName: string
        inputType: number,
        values: string
    }
    bodyNotNull(ctx, ['groupId', 'attrName', 'inputType', 'values'])
    const { userId } = ctx.global.tokenInfo
    // attrRepository
    //     .createQueryBuilder()
    //     .insert()
    //     .values([new Attr({ userId, groupId, attrName, inputType })])
    await query(`
        INSERT INTO attr (user_id, group_id, attr_name, input_type, value)
        SELECT ${escape(userId)}, ${escape(groupId)}, ${escape(attrName)}, ${escape(inputType)}, ${escape(values)}
        FROM DUAL
        WHERE NOT EXISTS (
            SELECT * FROM attr WHERE user_id = ${escape(userId)} AND group_id = ${escape(groupId)} AND attr_name = ${escape(attrName)} AND state=1
        );
    `).then(r => {
        ctx.body = new successRes()
    }).catch(e => {
        if (e === sqlErrorCode.exists) throw new errorRes('该分类存在相同的名称')
        throw new Error(e)
    })
})

export default router